import { onMounted, onBeforeUnmount, reactive, toRefs } from 'vue';

function useMousePosition() {
    const state = reactive({
        x: 0,
        y: 0
    })

    /* mousemove事件监听器 */
    const mousemoveHandler = e => {
        // console.log(e.pageX, e.pageY);
        state.x = e.pageX
        state.y = e.pageY
    }

    /* 在组件挂载完毕后监听mousemove事件 */
    onMounted(
        () => {
            document.body.addEventListener(
                "mousemove",
                mousemoveHandler
            )
        }
    )

    /* 组件卸载时清除相应的DOM事件监听器 以避免内存泄漏 */
    onBeforeUnmount(() => {
        document.body.removeEventListener(
            "mousemove",
            mousemoveHandler
        )
        console.log("mousemoveHandler 已移除");
    })

    return {
        ...toRefs(state)
    }
}

export default useMousePosition